package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.ExportExample;
import cn.itcast.domain.cargo.ExportProduct;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.utils.BeanMapUtils;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ExportProductVo;
import cn.itcast.vo.ExportResult;
import cn.itcast.vo.ExportVo;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.*;

@Controller
@RequestMapping("/cargo/export")
public class ExportController extends BaseController {
    @Reference
    private ContractService contractService;
    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;
    @Autowired
    private DownloadUtil downloadUtil;

    @RequestMapping(value = "/contractList",name = "查看已上报合同列表")
    public String contractList(@RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "10")Integer pageSize){
        ContractExample example = new ContractExample();
        example.createCriteria().andCompanyIdEqualTo(getCompanyId()).andStateEqualTo(1);
        PageInfo pageInfo = contractService.findAll(example, page, pageSize);
        request.setAttribute("page",pageInfo);
        return "cargo/export/export-contractList";
    }

    @RequestMapping(value = "/list",name = "查看已报运合同列表")
    public String list(@RequestParam(defaultValue = "1")Integer page,@RequestParam(defaultValue = "10")Integer pageSize){
        ExportExample example = new ExportExample();
        example.createCriteria().andCompanyIdEqualTo(getCompanyId());
        PageInfo pageInfo = exportService.findAll(example, page, pageSize);
        request.setAttribute("page",pageInfo);
        return "cargo/export/export-list";
    }

    @RequestMapping(value = "/toExport",name = "进入新增出口报运单页面")
    public String toExport(String id){
        request.setAttribute("id",id);
        return "cargo/export/export-toExport";
    }

    @RequestMapping(value = "/toUpdate",name = "进入新增出口报运单页面")
    public String toUpdate(String id){
        Export export = exportService.findById(id);
        request.setAttribute("export",export);
        List<ExportProduct> exportProductList = exportProductService.findByExportId(id);
        request.setAttribute("eps", exportProductList);
        return "cargo/export/export-update";
    }

    @RequestMapping(value = "/edit", name = "保存出口报运单信息")
    public String save(Export export) {
        if (StringUtils.isEmpty(export.getId())) {
            export.setId(UUID.randomUUID().toString().replace("-",""));
            export.setCreateBy(getUser().getId());
            export.setCreateDept(getUser().getDeptId());
            export.setCreateTime(new Date());
            export.setCompanyId(getCompanyId());
            export.setCompanyName(getCompanyName());
            exportService.save(export);
        } else {
            exportService.update(export);
        }
        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping(value = "/toView",name = "查看报运单")
    public String toView(String id){
        Export export = exportService.findById(id);
        request.setAttribute("export",export);
        return "cargo/export/export-view";
    }

    @RequestMapping(value = "/submit",name = "提交报运单")
    public String submit(String id){
        Export export = new Export();
        export.setId(id);
        export.setState(1);
        exportService.update(export);
        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping(value = "/cancel",name = "取消报运")
    public String cancel(String id){
        Export export = new Export();
        export.setId(id);
        export.setState(0);
        exportService.update(export);
        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping(value = "/delete",name = "删除报运单")
    public String delete(String id){
        exportService.delete(id);
        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping(value = "/exportE",name = "海关电子报运")
    public String exportE(String id){
        // 将Export对象转成ExportVo对象
        ExportVo exportVo = new ExportVo();
        Export export = exportService.findById(id);
        BeanUtils.copyProperties(export,exportVo);
        exportVo.setExportId(id);

        // 将ExportProduct对象转成ExportProductVo对象
        List<ExportProductVo> exportProductVoList = new ArrayList<>();
        List<ExportProduct> exportProductList = exportProductService.findByExportId(id);
        for (ExportProduct exportProduct : exportProductList) {
            ExportProductVo exportProductVo = new ExportProductVo();
            BeanUtils.copyProperties(exportProduct,exportProductVo);
            exportProductVo.setEid(exportVo.getId());
            exportProductVo.setExportProductId(exportProduct.getId());
            exportProductVoList.add(exportProductVo);
        }

        // 发送消息到海关报运项目
        exportVo.setProducts(exportProductVoList);
        WebClient.create("http://localhost:9090/ws/export/ep").post(exportVo);

        // 接收海关项目返回的数据
        ExportResult exportResult = WebClient.create("http://localhost:9090/ws/export/ep/" + id).get(ExportResult.class);
        exportService.updateE(exportResult);

        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping(value = "/exportPdf",name = "下载出口商品报运单pdf")
    public void exportPdf(String id){
        Export export = exportService.findById(id);
        List<ExportProduct> productList = exportProductService.findByExportId(id);
        try {
            String path = session.getServletContext().getRealPath("/make/jasper/export.jasper");
            FileInputStream in = new FileInputStream(path);
            Map<String, Object> map = BeanMapUtils.beanToMap(export);
            JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(productList);
            JasperPrint jasperPrint = JasperFillManager.fillReport(in, map, dataSource);

            byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byteArrayOutputStream.write(bytes);
            downloadUtil.download(byteArrayOutputStream,response,"报运单.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
